package com.jie.erp.springbootjieerp.service.impl;

import com.jie.erp.springbootjieerp.bean.JepRole;
import com.jie.erp.springbootjieerp.bean.JepUser;
import com.jie.erp.springbootjieerp.bean.UserRole;
import com.jie.erp.springbootjieerp.mapper.JepUserMapper;
import com.jie.erp.springbootjieerp.service.JepRoleService;
import com.jie.erp.springbootjieerp.service.JepUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JepUserServiceImpl implements JepUserService {

    @Autowired
    JepUserMapper jepUserMapper;

    @Autowired
    JepRoleService jepRoleService;

    @Override
    public JepUser selectByUserAndPass(String username,String password) {
        Map<String,String> map=new HashMap<String,String>();
        map.put("username",username);
        map.put("password",password);
        return jepUserMapper.selectByUserAndPass(map);
    }

    @Override
    public List<JepUser> selectUsers() {
        return jepUserMapper.selectUsers();
    }

    @Override
    public List<JepRole> selectUserAndRole(Integer userId) {
        List<JepRole> roleAll = jepRoleService.getRoleAll();
        JepUser jepUser = jepUserMapper.selectUserRole(userId);
        if(roleAll!=null&&jepUser!=null){
        List<JepRole> roles = jepUser.getRoles();
            for (JepRole role:roleAll){
                for (JepRole role1:roles){
                    if(role.getRoleId().intValue()==role1.getRoleId().intValue()){
                        role.setSelected("yes");
                    }
                }
            }
        }
        return roleAll;
    }

    @Override
    public void assignRoleByUser(Integer userId, String roles) {
        List<UserRole> userRoleList=new ArrayList<UserRole>();
        String[] roleIdArr=null;
        if(roles!=null&&!"".equals(roles)){
            roleIdArr=roles.split(",");
        for (String roleId:roleIdArr){
            UserRole userRole=new UserRole();
            userRole.setRoleId(new Integer(roleId));
            userRole.setUserId(userId);
            userRoleList.add(userRole);
         }
        }
        jepRoleService.granRole(userRoleList,userId);
     }

    @Override
    public JepUser getUserById(Integer userId) {
        return jepUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    public void deleteUserById(Integer userId) {
        jepUserMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public void saveUser(JepUser user) {
        jepUserMapper.insert(user);
    }

    @Override
    public void updateUser(JepUser user) {
        jepUserMapper.updateByPrimaryKeySelective(user);
    }

}
